﻿#include "QLog.h"
#include <QDate>
#include <QDir>
#include <QDebug>
#include <QCoreApplication>
#include <fstream>


// 扑捉到程序崩溃或者中断时，把相应的信息打印到log文件和输出到屏幕。
void SignalHandler(const char *data, size_t size)
{
    QString logPath = QCoreApplication::applicationDirPath() + "/log/Crash";
    //若crash文件夹不存在则创建
    QDir logPathDir(logPath);
    if(!logPathDir.exists()){
        QDir().mkpath(logPathDir.absolutePath());
    }
    //组织文件名称
    QString strTime = QDateTime::currentDateTime().toString("yyyy-MM-dd_hh:mm:ss");
    logPath = logPath + "/"+ strTime + ".log";
    std::string glog_file = logPath.toStdString();

    //创建文件
    std::ofstream fs(glog_file, std::ios::app);

    //打印到文件
    std::string str = std::string(data, size);
    fs << str;
    fs.close();

    //打印到控制台
    LOG(ERROR) << str;
}

QLog::QLog()
{
    QString appDir = QCoreApplication::applicationDirPath();
    QDir dir;
    if(!dir.exists(appDir + "/log/Info"))
        dir.mkpath(appDir + "/log/Info");
    if(!dir.exists(appDir + "/log/Warning"))
        dir.mkpath(appDir + "/log/Warning");
    if(!dir.exists(appDir + "/log/Error"))
        dir.mkpath(appDir + "/log/Error");

    deleteOldLog();

    google::InitGoogleLogging(QCoreApplication::applicationName().toStdString().data());

    google::SetStderrLogging(google::GLOG_WARNING); //设置级别高于 google::INFO 的日志同时输出到屏幕
    google::SetLogDestination(google::GLOG_INFO, QString(appDir + "/log/Info/Info_").toStdString().data()); //设置 google::INFO 级别的日志存储路径和文件名前缀
    google::SetLogDestination(google::GLOG_WARNING, QString(appDir + "/log/Warning/Warning_").toStdString().data());   //设置 google::WARNING 级别的日志存储路径和文件名前缀
    google::SetLogDestination(google::GLOG_ERROR, QString(appDir + "/log/Error/Error_").toStdString().data());   //设置 google::ERROR 级别的日志存储路径和文件名前缀
    google::SetLogFilenameExtension(".log");     //设置文件名扩展

    google::InstallFailureSignalHandler(); //注册一下即可。默认是打印到stderr中，可以通过InstallFailureWriter更改输出目标,输出崩溃日志
    google::InstallFailureWriter(&SignalHandler);

    FLAGS_colorlogtostderr = true;    //设置输出到屏幕的日志显示相应颜色
    FLAGS_logbufsecs = 0;        //缓冲日志输出，默认为30秒，此处改为立即输出
    FLAGS_max_log_size = 100;    //最大日志大小为 100MB
    FLAGS_stop_logging_if_full_disk = true;     //当磁盘被写满时，停止日志输出

    LOG(INFO) << "app start";
}
QLog::~QLog()
{
    LOG(INFO) << "app exit";
    google::ShutdownGoogleLogging();
}

void QLog::deleteOldLog()
{
    QString appDir = QCoreApplication::applicationDirPath();
    int days = 7;
    const QDate today = QDate::currentDate();

    auto deleteLog = [days, today](QString dir){
        Q_FOREACH(auto  fileInfo, QDir(dir).entryInfoList())
        {
            if (fileInfo.birthTime().date().daysTo(today) > days)
            {
                QString filepath = fileInfo.absoluteFilePath();
                QDir deletefile;
                deletefile.setPath(filepath);
                if (deletefile.remove(filepath)){
                    qDebug() << "File " + filepath + " is deleted!";
                }
            }
        }
    };
    deleteLog(appDir + "/log/INFO");
    deleteLog(appDir + "/log/WARNING");
    deleteLog(appDir + "/log/ERROR");

}
